package cn.witeye.vpais.ga1400.utils;


import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * ImageKit 图片高保真缩放与裁剪，不依赖于任何第三方库
 */
@Slf4j
public class ImageKit {

	/**
	 * 对图片进行剪裁，只保存选中的区域
	 */
	public static byte[] crop(byte[] data, int x, int y, int w, int h) {
		ByteArrayInputStream bis = null;
		ByteArrayOutputStream bos = null;
		try {
			// 从byte[]中读取数据
			bis = new ByteArrayInputStream(data);
			BufferedImage bi = ImageIO.read(bis);

			int left = x;
			int top = y;
			int width = w;
			int height = h;

			width = Math.min(width, bi.getWidth());
			height = Math.min(height, bi.getHeight());
			if (width <= 0) {
				width = bi.getWidth();
			}
			if (height <= 0) {
				height = bi.getHeight();
			}

			left = Math.min(Math.max(0, left), bi.getWidth() - width);
			top = Math.min(Math.max(0, top), bi.getHeight() - height);

			// 裁剪指定区域图片
			BufferedImage newBi = bi.getSubimage(left, top, width, height);

			// 把裁剪的图片保存为byte[]
			bos = new ByteArrayOutputStream();
			boolean ret = ImageIO.write(newBi, "jpg", bos);
			if (ret == false) {
				log.warn("保存为ByteArrayOutputStream失败");
				return null;
			}
			return bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			log.warn("", e);
			return null;
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
				}
			}
		}
	}

}
